package com.lumeijin.service;

import com.lumeijin.entity.User;
import com.lumeijin.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class UserService {
    private final UserRepository userRepository;
    private final SmsService smsService;
    private final PasswordEncoder passwordEncoder;
    
    public String registerUser(String username, String password, String email, String phone, String smsCode) {
        if (!smsService.verifySmsCode(phone, smsCode)) {
            return "验证码错误或已过期";
        }
        if (userRepository.existsByUsername(username)) {
            return "用户名已存在";
        }
        if (userRepository.existsByEmail(email)) {
            return "邮箱已存在";
        }
        if (userRepository.existsByPhone(phone)) {
            return "手机号已存在";
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setEmail(email);
        user.setPhone(phone);
        userRepository.save(user);
        return "注册成功";
    }
    
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    
    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }
    
    public String uploadAvatar(Long userId, MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件不能为空";
            }
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return "只能上传图片文件";
            }
            if (file.getSize() > 5 * 1024 * 1024) {
                return "文件大小不能超过5MB";
            }
            String uploadDir = "/root/lumeijin/uploads/";
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null) {
                int dotIndex = originalFilename.lastIndexOf('.');
                if (dotIndex >= 0) {
                    extension = originalFilename.substring(dotIndex);
                }
            }
            if (extension.isEmpty() && contentType != null && contentType.contains("/")) {
                String subtype = contentType.substring(contentType.indexOf('/') + 1);
                extension = "." + subtype.replaceAll("[^a-zA-Z0-9]", "");
            }
            String filename = UUID.randomUUID().toString() + extension;
            Path filePath = Paths.get(uploadDir + filename);
            Files.copy(file.getInputStream(), filePath);
            Optional<User> userOpt = userRepository.findById(userId);
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                user.setAvatarUrl("/uploads/" + filename);
                userRepository.save(user);
                return "头像上传成功";
            } else {
                return "用户不存在";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败";
        }
    }
    
    public boolean verifyPassword(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }
    
    public User updateUser(User user) {
        return userRepository.save(user);
    }
}
